package com.naiterui.ehp.bs.weixin.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.naiterui.ehp.bs.weixin.config.SubscribeConfig;
import com.naiterui.ehp.bs.weixin.config.WxMaConfiguration;
import com.naiterui.ehp.bs.weixin.constant.WxMaConstants;
import com.naiterui.ehp.bs.weixin.properties.WeixinProperties;
import com.naiterui.ehp.bs.weixin.service.ISubscribeNoticeService;
import com.naiterui.ehp.bs.weixin.subscribe.BaseSubscribe;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeMsg;
import com.naiterui.ehp.bs.weixin.subscribe.SubscribeProperties;
import com.naiterui.ehp.bs.weixin.wechat.WeChatApiUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 订阅消息
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/5/24 10:12
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class SubscribeNoticeServiceImpl implements ISubscribeNoticeService {
    private final SubscribeConfig subscribeConfig;
    private final WeixinProperties weixinproperties;

    @Override
    public Integer notice(BaseSubscribe param) {
        if (null == param || !param.validate()) {
            log.error("订阅通知发送失败，参数错误: {}", param);
            return 47003;
        }

        //通过label查询模板配置，来获取微信的templateId以及基础文案
        SubscribeProperties subscribeProperties = Optional.ofNullable(param.getTemplateLabel())
                .map(label -> subscribeConfig.templateMap().get(label)).get();
        if (null == subscribeProperties) {
            log.info("模板配置信息不全，请添加配置到subscribe-template.yml，配置: {}", subscribeProperties);
            return 47003;
        }

        //处理模板内容
        List<SubscribeProperties.Content> contentList = subscribeProperties.cloneContent();
        // 格式化处理文本内容
        param.handleContent(contentList);
        Map<String, Object> dataMap = contentList.stream()
                .collect(Collectors.toMap(SubscribeProperties.Content::getKey, SubscribeProperties.Content::getValue));
        return this.sendSubscribe(param.getOpenId(), subscribeProperties.getTemplateId(), param.getTargetPage(), dataMap);
    }

    private Integer sendSubscribe(String openId, String templateId, String url, Map<String, Object> data) {
//        return WeChatApiUtil.sendSubscribeMsg(accessTokenService.accessToken(), SubscribeMsg.builder()
//                .toUser(openId)
//                .templateId(templateId)
//                .page(url)
//                .data(createDataMap(data))
//                .miniprogramState(WxMaConstants.MiniProgramState.FORMAL)
//                .lang(WxMaConstants.MiniProgramLang.ZH_CN)
//                .build());
        String appId = weixinproperties.getAppId();
        WxMaService wxMaService = WxMaConfiguration.getMaService(appId);
        Integer errcode = 0;
        try {
            errcode = WeChatApiUtil.sendSubscribeMsg(wxMaService.getAccessToken(), SubscribeMsg.builder()
                    .toUser(openId)
                    .templateId(templateId)
                    .page(url)
                    .data(createDataMap(data))
                    .miniprogramState(WxMaConstants.MiniProgramState.FORMAL)
                    .lang(WxMaConstants.MiniProgramLang.ZH_CN)
                    .build());
        } catch (WxErrorException e) {
            log.warn("发送订阅消息失败", e);
        }

        return errcode;
    }

    private Map<String, SubscribeMsg.Data> createDataMap(Map<String, Object> source) {
        Map<String, SubscribeMsg.Data> dataMap = new HashMap<>(16);
        source.keySet().forEach(key -> dataMap.put(key, new SubscribeMsg.Data(source.get(key))));
        return dataMap;
    }
}
